package com.xpqh.ksg.common.utils;

import com.alibaba.fastjson.JSON;
import com.xpqh.ksg.modular.warranty.dto.ImageinfoDto;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class ImageInfoFetcher {

    public static ImageinfoDto getImageInfo(String imageUrl) {
        try {
            // 从URL加载图片
            BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl));

            if (bufferedImage != null) {
                // 获取图片基本信息
                int width = bufferedImage.getWidth();
                int height = bufferedImage.getHeight();
                String formatName = "unknown";

                // 确定图片格式
                for (String format : ImageIO.getReaderFormatNames()) {
                    if (imageUrl.toLowerCase().endsWith("." + format.toLowerCase())) {
                        formatName = format;
                        break;
                    }
                }
                ImageinfoDto imageinfoDto = new ImageinfoDto();
                IdGenerator idGenerator = new IdGenerator(1); // 节点ID为1
                imageinfoDto.setFileid(idGenerator.nextId()+"");
                imageinfoDto.setPath(imageUrl);
                imageinfoDto.setSize(getFileSizeFromUrl(imageUrl));
                imageinfoDto.setExtension(formatName);
                imageinfoDto.setContentType("image/"+formatName);

                Map<String, Integer> dimension = new HashMap<>();
                dimension.put("width", width);
                dimension.put("height", height);
                imageinfoDto.setFileMd5(UUID.randomUUID().toString());
                String json = JSON.toJSONString(dimension);
                imageinfoDto.setMate(json);
                return imageinfoDto;
            } else {
                System.out.println("Failed to load image.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }
    public static long getFileSizeFromUrl(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("HEAD"); // 只请求头信息，不下载整个文件
        httpConn.connect();

        return httpConn.getContentLengthLong(); // 返回文件大小（字节数）
    }

    public static void main(String[] args) {
        // 调用示例
        String imageUrl = "https://oss.h-ksg.com/ksg_qxImg20250625193137715742.jpg";
        getImageInfo(imageUrl);
    }
}
